import { Button, Col, Form, Row } from 'antd';
import React from 'react';
import { FormComponentProps } from 'antd/es/form';
import styles from '../index.less';
import { getFieldDefines, getFormInputByField } from '../utils';
import { Field } from '@/dictionary/index.d';

const FormItem = Form.Item;

interface SearchFormProps extends FormComponentProps {
  visible: boolean; // 是否显示
  config: any; // 配置项
  onSubmit: (values: any) => void; // 查询提交事件
  dictionary: Field[];
}

const SearchForm: React.FC<SearchFormProps> = props => {
  const { form, visible, onSubmit, config, dictionary } = props;
  const { getFieldDecorator, validateFields } = form;
  const { fields } = config;

  const handleFormReset = () => {
    form.resetFields();
  };

  const handleSubmit = (e: any) => {
    e.preventDefault();
    validateFields((err, values) => {
      if (!err) {
        onSubmit(values);
      }
    });
  };

  return visible ? (
    <Form layout="inline" onSubmit={handleSubmit}>
      <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
        {getFieldDefines(fields, dictionary).map(field => {
          const content = (
            <Col md={8} sm={24} key={field.name}>
              <FormItem label={field.desc}>
                {getFieldDecorator(field.name)(getFormInputByField(field))}
              </FormItem>
            </Col>
          );
          return content;
        })}
        <Col md={8} sm={24}>
          <span className={styles.submitButtons}>
            <Button type="primary" htmlType="submit" icon="search">
              查询
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleFormReset}>
              重置
            </Button>
          </span>
        </Col>
      </Row>
    </Form>
  ) : (
    <span />
  );
};

export default Form.create<SearchFormProps>()(SearchForm);
